//
//  ZYCTeaLeaveApproverViewController.m
//  ZDSC
//
//  Created by 张威 on 2021/10/26.
//

#import "ZYCTeaLeaveApproverViewController.h"
#import "ZYCSearchBarView.h"
#import "ZYCTeaLeaveApproverMultipleChoiceView.h"
#import "ZYCTeaLeaveApproverCell.h"
#import "ZYCTeaLeaveApproverHeaderView.h"

#import "BTImageTitleButton.h"


@interface ZYCTeaLeaveApproverViewController ()<UITableViewDataSource,UITableViewDelegate,ZYCTeaLeaveApproverMultipleChoiceViewDelegate,ZYCSearchBarViewDelegate,ZYCTeaLeaveApproverHeaderViewDelegate,ZYCSearchBarViewDelegate>

@property (nonatomic, strong) ZYCSearchBarView *searchView;
@property (nonatomic, strong) UIButton *comfirmButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ZYCTeaLeaveApproverMultipleChoiceView *fliterView;

@property (nonatomic, strong) ZYCTeaLeaveApproverHeaderView *headerView;
@property (nonatomic, strong) NSMutableArray *selectArr;
@property (nonatomic, strong) NSMutableArray *allUserIdsArray;
// 关键字搜索
@property (nonatomic, copy) NSString *keyword;
//搜索人数
@property (nonatomic, strong) NSArray *searchResultArray;
//

@end

@implementation ZYCTeaLeaveApproverViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择审批人";
    [self.view addSubview:self.searchView];
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    self.headerView.applyNode = self.model.applyNode;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.comfirmButton];
    [self getUserListByNodeId];

    for (ZYCTeaLeaveApplyUserModel *m in self.model.applyUserList) {
        [self.selectArr addObject:m.userId];
    }
    if (self.selectArr.count > 0) {
        [self.comfirmButton setTitle:[NSString stringWithFormat:@"确认(%zd)",self.selectArr.count] forState:UIControlStateNormal];
        [self.comfirmButton sizeToFit];
    }
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCTeaLeaveApplyUserModel *model = self.dataSource[indexPath.row];
    ZYCTeaLeaveApproverCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCTeaLeaveApproverCell class]) forIndexPath:indexPath];
    cell.model = model;
    if ([self.selectArr containsObject:model.userId]) {
        cell.select = YES;
    } else {
        cell.select = NO;
    }
    return cell;
}



-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 58.0f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ZYCTeaLeaveApproverCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    ZYCTeaLeaveApplyUserModel *model = self.dataSource[indexPath.row];
    if (cell.select) {
        cell.select = NO;
        [self.selectArr removeObject:model.userId];
    }else{
        cell.select = YES;
        [self.selectArr addObject:model.userId];
    }
    BTImageTitleButton *selectButton = self.headerView.selectButton;
    if (self.selectArr.count == self.dataSource.count) {
        selectButton.selected = YES;
    }else{
        selectButton.selected = NO;
    }
    [self.comfirmButton setTitle:[NSString stringWithFormat:@"确认(%zd)",self.selectArr.count] forState:UIControlStateNormal];
    [self.comfirmButton sizeToFit];

    [self.tableView reloadData];
}


#pragma mark - ZYCSearchBarViewDelegate
- (void)searchBarViewDidTextDidChange:(NSString *)searchText height:(CGFloat)height{
    self.fliterView.frame = CGRectMake(0, CGRectGetMaxY(self.searchView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.searchView.frame) - height);
    NSLog(@"搜索关键字:%@",searchText);
    self.keyword = searchText;
    if (searchText.length > 0) {
        self.fliterView.hidden = NO;
        self.tableView.hidden = YES;
    }else{
        self.fliterView.hidden = YES;
        self.tableView.hidden = NO;
    }
}
#pragma mark - setters
- (void)setKeyword:(NSString *)keyword{
    _keyword = keyword;
    if (!keyword || keyword.length <= 0) {
        self.searchResultArray = self.dataSource;
    }else{
        NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"realName contains[c] %@", keyword];
        self.searchResultArray = [self.dataSource filteredArrayUsingPredicate:filterPredicate];
    }
    self.fliterView.dataSource = self.searchResultArray;
    [self.fliterView refresh];
}

#pragma mark - ZYCTeaLeaveApproverMultipleChoiceViewDelegate
- (void)teaLeaveApproverMultipleChoiceView:(ZYCTeaLeaveApproverMultipleChoiceView *)view selectArr:(NSArray *)selectArr{
    [self.selectArr removeAllObjects];
//    for (ZYCRoleTreeModel *model in selectArr) {
//        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//        [dict setObject:model.r_id forKey:@"userId"];
//        [dict setObject:model.label forKey:@"userName"];
//        [self.selectArray addObject:dict];
//    }

    [self.comfirmButton setTitle:[NSString stringWithFormat:@"确认(%zd)",selectArr.count] forState:UIControlStateNormal];
    [self.comfirmButton sizeToFit];
}

#pragma mark - ZYCTeaLeaveApproverHeaderViewDelegate

// 点击全选
- (void)teaLeaveApproverHeaderViewClickAllSelect:(BOOL)isAllSelect{
    if (isAllSelect) {// 全选
        [self.selectArr removeAllObjects];
        [self.selectArr addObjectsFromArray:self.allUserIdsArray];

        [self.comfirmButton setTitle:[NSString stringWithFormat:@"确认(%zd)",self.selectArr.count] forState:UIControlStateNormal];
        [self.comfirmButton sizeToFit];
        
//        for (ZYCTeaLeaveApplyUserModel *model in self.dataSource) {
//            model.isSelected = YES;
//        }
//        self.searchResultArray = self.dataSource;
//        self.fliterView.dataSource = self.searchResultArray;
//        [self.fliterView refresh];
        
    }else{
        [self.selectArr removeAllObjects];
        [self.comfirmButton setTitle:@"确认" forState:UIControlStateNormal];
        [self.comfirmButton sizeToFit];
    }
    

    
    [self.tableView reloadData];
}
#pragma mark - ZYCSearchBarViewDelegate



#pragma mark - getters

- (NSArray *)searchResultArray {
    if (!_searchResultArray) {
        _searchResultArray = [[NSArray alloc] init];
    }
    return _searchResultArray;
}

- (ZYCTeaLeaveApproverHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ZYCTeaLeaveApproverHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50.0f)];
        _headerView.delegate = self;
    }
    return _headerView;
}
- (NSMutableArray *)selectArr {
    if (!_selectArr) {
        _selectArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _selectArr;
}

- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [[NSArray alloc] init];
    }
    return _dataSource;
}
- (ZYCSearchBarView *)searchView {
    if (!_searchView) {
        _searchView = [[ZYCSearchBarView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, 63.0f)];
        _searchView.delegate = self;

    }
    return _searchView;
}
- (UIButton *)comfirmButton {
    if (!_comfirmButton) {
        _comfirmButton = [[UIButton alloc] init];
        [_comfirmButton setTitle:@"确认" forState:UIControlStateNormal];
        [_comfirmButton setTitleColor:HEX_RGB(kTitleWhiteColor) forState:UIControlStateNormal];
        _comfirmButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 15.0f);
        [_comfirmButton addTarget:self action:@selector(clickRightItem:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _comfirmButton;
}



- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.searchView.frame)) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCTeaLeaveApproverCell class] forCellReuseIdentifier:NSStringFromClass([ZYCTeaLeaveApproverCell class])];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
    }
    return _tableView;
}

- (ZYCTeaLeaveApproverMultipleChoiceView *)fliterView {
    if (!_fliterView) {
        _fliterView = [[ZYCTeaLeaveApproverMultipleChoiceView alloc] initWithFrame:self.tableView.frame];
        _fliterView.hidden = YES;
        _fliterView.delegate = self;

        [self.view addSubview:_fliterView];
    }
    return _fliterView;
}

- (NSMutableArray *)allUserIdsArray {
    if (!_allUserIdsArray) {
        _allUserIdsArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _allUserIdsArray;
}


#pragma mark - private method

- (void)clickRightItem:(UIButton *)sender{
    NSMutableArray *temp = [NSMutableArray arrayWithCapacity:0];
    for (ZYCTeaLeaveApplyUserModel *model in self.dataSource) {
        if ([self.selectArr containsObject:model.userId]) {
            [temp addObject:model];
        }
    }
    if (self.selectApproverBlock) {
        self.selectApproverBlock(temp);
    }
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 网络请求
- (void)getUserListByNodeId{
    NSDictionary *params = @{
        @"nodeId":self.model.applyNodeId
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_UserListByNodeId requestService:RequestServiceActiviti parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        [MrjSVProgressHUD dismiss];
        if (SUCCESS(responseObject[@"code"])) {
            self.dataSource = [NSArray yy_modelArrayWithClass:[ZYCTeaLeaveApplyUserModel class] json:responseObject[@"body"]];
            for (ZYCTeaLeaveApplyUserModel *model in self.dataSource) {
                [self.allUserIdsArray addObject:model.userId];
                if (self.selectArr.count == self.dataSource.count) {
                    BTImageTitleButton *selectButton = self.headerView.selectButton;
                    selectButton.selected = YES;
                }
                if ([self.selectArr containsObject:model.userId]) {
                    model.isSelected = YES;
                }else{
                    model.isSelected = NO;
                }
            }
            // 搜索框列表
            self.searchResultArray = self.dataSource;
            self.fliterView.dataSource = self.searchResultArray;
            [self.fliterView refresh];
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
